<template>
  <div class="app-container">
    <!-- 查询框 -->
    <div class="filter-container">
      <el-input style="width: 200px;" v-model="pageParam.superSearchKeyWord" placeholder="关键字查询..." class="filter-item"
        @keyup.enter.native="handleFilter" @input="handleFilter" />
      <!-- <el-select style="width: 140;" v-model="pageParam.orderParams" class="filter-item" placeholder="创建时间">
        <el-option v-for="item in createTimeOrderOptions" :key="item.key" :label="item.label" :value="item.value" />
      </el-select> -->
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        添加
      </el-button>
    </div>

    <!-- 表格 -->
    <el-table :data="list" @sort-change="sortChange" fit highlight-current-row style="width: 100%;">

      <el-table-column class="filter-item" type="expand">
        <template slot-scope="{row}">
          <el-form label-position="left" inline class="demo-table-expand">
            <el-form-item label="真实姓名">
              <span>{{ row.realName }}</span>
            </el-form-item>
            <el-form-item label="昵称">
              <span>{{ row.nickName }}</span>
            </el-form-item>
            <el-form-item label="账号">
              <span>{{ row.userName }}</span>
            </el-form-item>
            <el-form-item label="创建时间">
              <span>{{ row.createTime }}</span>
            </el-form-item>
            <el-form-item label="年龄">
              <span>{{ row.age }}</span>
            </el-form-item>
            <el-form-item label="生日">
              <span>{{ row.birth }}</span>
            </el-form-item>
            <el-form-item label="角色">
              <span>{{ row.roleName }}</span>
            </el-form-item>
            <el-form-item label="个性签名">
              <span>{{ row.comment }}</span>
            </el-form-item>
          </el-form>
        </template>
      </el-table-column>
      <el-table-column prop="roleName" label="角色">
      </el-table-column>
      <el-table-column prop="userName" label="账号">
      </el-table-column>
      <el-table-column prop="realName" label="真实姓名">
      </el-table-column>
      <el-table-column prop="nickName" label="昵称">
      </el-table-column>
      <el-table-column sortable="custom" prop="age" label="年龄">
      </el-table-column>
      <el-table-column sortable="custom" prop="createTime" label="创建时间">
      </el-table-column>

      <el-table-column label="操作" fit>
        <template slot-scope="{row,$index}">
          <el-button type="primary" @click="handleUpdate(row)">编辑</el-button>
          <el-button type="danger" @click="handleDelete(row,$index)">删除</el-button>
        </template>
      </el-table-column>

    </el-table>

    <!-- 分页组件 -->
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.pageNum" :limit.sync="listQuery.pageSize"
      @pagination="getListByPage" />
    <!-- 弹窗组件 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="right" label-width="70px" style="width: 400px; margin-left:50px;">

        <el-form-item label="账号" prop="userName">
          <el-input v-model="temp.userName" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="temp.password" />
        </el-form-item>

        <el-form-item label="角色" prop="roleId">
          <el-select @change="setRoleData($event)" v-model="temp.roleId" placeholder="请选择角色">
            <el-option v-for="item in roleList" :key="item.id" :label="item.roleName" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="生日" prop="birth">
          <el-date-picker v-model="temp.birth" type="datetime" placeholder="Please pick a date" />
        </el-form-item>
        <el-form-item label="真实姓名" prop="realName">
          <el-input v-model="temp.realName" />
        </el-form-item>
        <el-form-item label="个性签名" prop="comment">
          <el-input v-model="temp.comment" />
        </el-form-item>
        <el-form-item label="昵称" prop="nickName">
          <el-input v-model="temp.nickName" />
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input v-model="temp.age" />
        </el-form-item>

        <el-form-item label="性别" prop="gender">
          <el-select v-model="temp.gender" placeholder="请选择性别">
            <el-option label="男" value="1">
            </el-option>
            <el-option label="女" value="0">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="头像">
          <el-upload class="avatar-uploader" name="image" :headers="headerToken"  action="http://localhost:5050/file/uploadImage"
            :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
            <img v-if="temp.headPic" :src="temp.headPic" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>


      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          确认
        </el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="dialogPvVisible" title="Reading statistics">
      <el-table :data="pvData" border fit highlight-current-row style="width: 100%">
        <el-table-column prop="key" label="Channel" />
        <el-table-column prop="pv" label="Pv" />
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogPvVisible = false">确认</el-button>
      </span>
    </el-dialog>




  </div>
</template>

<script>
  import { getToken } from '@/utils/auth'
  //导入user的api
  import {
    searchSomeUserByPage,
    addOneUser,
    deleteOneUserTrue,
    updateUser
  } from '@/api/user'
  import {
    searchSomeRoleByPage
  } from '@/api/role'
  //导入组件  记得声明组件
  import Pagination from '@/components/Pagination'

  export default {
    components: { //在这里声明组件
      Pagination
    },
    data() {
      return {
        headerToken:{
          'Authorization': getToken()
        },
        list: [], //列表数据
        total: 0,
        createTimeOrderOptions: [{
            label: '创建时间 升序',
            key: '+createTime',
            value: 'createTime asc'
          },
          {
            label: '创建时间 降序',
            key: 'createTime',
            value: 'createTime desc'
          }
        ],

        listQuery: { //分页 排序  查询参数
          pageNum: 1,
          pageSize: 6
        },
        fieldQuery: { // 按字段查询
          realName: ''
        },
        dialogFormVisible: false,
        dialogStatus: '',
        textMap: {
          update: '编辑',
          create: '创建'
        },
        dialogPvVisible: false,
        pvData: [],
        temp: {
          id: undefined,
          realName: '',
          nickName: '',
          age: undefined,
          birth: undefined,
          roleId: '',
          roleName: '',
          roleSign: '',
          userName: '',
          headPic: '',
          gender: 0,
          comment: ''
        },
        rules: {
          userName: [{
              required: true,
              message: '账号不能为空',
              trigger: 'blur'
            },
            {
              min: 5,
              max: 20,
              message: '长度在 5 到 20 个字符',
              trigger: 'blur'
            }
          ],
          password: [{
              required: true,
              message: '密码不能为空',
              trigger: 'blur'
            },
            {
              min: 5,
              max: 1000,
              message: '密码长度必须超过 5 个字符',
              trigger: 'blur'
            }
          ],
          realName: [{
              required: true,
              message: '真实姓名不能为空',
              trigger: 'blur'
            },
            {
              min: 1,
              max: 6,
              message: '真实姓名长度必须在1到6之间',
              trigger: 'blur'
            }
          ],
          nickName: [{
              required: true,
              message: '昵称不能为空',
              trigger: 'blur'
            },
            {
              min: 1,
              max: 10,
              message: '昵称长度必须在1到10之间',
              trigger: 'blur'
            }
          ],
          age: [{
              required: true,
              message: '年龄不能为空',
              trigger: 'blur'
            }
          ],
        },
        pageParam: {
          pageNum: 1,
          pageSize: 6,
          model: {

          },
          orderParams: [
            'createTime desc'
          ],
          superSearchKeyWord: ''
        },
        roleList: []

      }
    },
    created() {
      this.getListByPage()
    },
    methods: {
      sortChange(val) {
        // console.log("排序参数",val)
        let prop = val.prop
        let order = val.order === 'ascending' ? 'asc' : 'desc'
        let orderParam = prop + ' ' + order
        // console.log(orderParam)
        for (let i = 0; i < this.pageParam.orderParams.length; i++) {
          if (this.pageParam.orderParams[i].indexOf(prop) > -1) {
            this.pageParam.orderParams.splice(i, 1)
          }
        }
        this.pageParam.orderParams.push(orderParam)
        console.log(this.pageParam.orderParams)
        this.getListByPage()
      },
      setRoleData(roleId) {
        console.log(roleId)
        for (let role of this.roleList) {
          if (roleId === role.id) {
            this.temp.roleId = role.id
            this.temp.roleSign = role.roleSign
            this.temp.roleName = role.roleName
            // console.log(role)
          }
        }
      },
      getAllRole() {
        let pageNum = 1
        let pageSize = 100
        let orderParams = []
        let model = {
            checkStatus:1  //只查询 已经审核通过的角色
          }
        let pageParam = {
          pageNum,
          pageSize,
          orderParams,
          model
        }

        searchSomeRoleByPage(pageParam).then(res => {
          // console.log(res)
          this.roleList = res.content.list
        }).catch(err => {
          console.log(err)
        })
      },
      getListByPage() {
        this.pageParam.pageNum = this.listQuery.pageNum
        this.pageParam.pageSize = this.listQuery.pageSize

        console.log(this.pageParam.orderParams)

        searchSomeUserByPage(this.pageParam).then(res => {
          // console.log(res)
          this.list = res.content.list
          this.total = res.content.total
        }).catch(err => {
          console.log(err)
        })
      },
      handleFilter() {
        this.listQuery.page = 1
        this.getListByPage()
      },
      handleCreate() {
        this.resetTemp()
        this.dialogStatus = 'create'
        this.dialogFormVisible = true
        this.getAllRole() //加载角色列表
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      handleUpdate(row) {
        this.temp = Object.assign({}, row) // copy obj
        this.temp.birth = new Date(this.temp.birth)
        this.dialogStatus = 'update'
        this.dialogFormVisible = true
        this.getAllRole() //加载角色列表
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      handleDelete(row, index) {

        let temp = {
          id: row.id
        }

        deleteOneUserTrue(temp).then(() => {
          this.dialogFormVisible = false
          this.$notify({
            title: '成功',
            message: '删除成功',
            type: 'success',
            duration: 2000
          })
          this.getListByPage()
        })

      },
      createData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            addOneUser(this.temp).then(() => {
              this.dialogFormVisible = false
              this.$notify({
                title: 'Success',
                message: 'Created Successfully',
                type: 'success',
                duration: 2000
              })
              this.getListByPage()
            })
          }
        })
      },
      updateData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            updateUser(this.temp).then(() => {
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '编辑成功',
                type: 'success',
                duration: 2000
              })
              this.getListByPage()
            })
          }
        })




      },
      resetTemp() {

      },
      handleAvatarSuccess(res, file) {
        // console.log(res,file)
        // this.temp.headPic = URL.createObjectURL(file.raw);
        this.temp.headPic = res.content
      },
      beforeAvatarUpload(file) {
        console.log(file)
        const fileName = file.name
        const isImage = /.(gif|jpg|jpeg|png|gif|jpg|png)$/.test(fileName);
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isImage) {
          this.$message.error('上传头像图片只能是 gif|jpg|jpeg|png|gif|jpg|png 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!');
        }
        return isImage && isLt2M;
      }
    }




  }
</script>

<style>
  .demo-table-expand {
    font-size: 0;
  }

  .demo-table-expand label {
    width: 90px;
    color: #99a9bf;
  }

  .demo-table-expand .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
    width: 50%;
  }

  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }

  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
